package cn.momoshenchi.service.impl;

import cn.momoshenchi.util.ParamsException;
import cn.momoshenchi.util.AssertUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.momoshenchi.pojo.Article;
import cn.momoshenchi.service.ArticleService;
import cn.momoshenchi.mapper.ArticleMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;

/**
 *
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
        implements ArticleService
{

    @Autowired
    private ArticleMapper articleMapper;


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public List<Article> search(String keyword)
    {
        return articleMapper.search(keyword);
    }

    @Override
    @Transactional(rollbackFor = ParamsException.class)
    public void insertWithEs(Article article) throws IOException
    {
        AssertUtil.isTrue(!this.save(article), "添加失败");
//        IndexRequest indexRequest = new IndexRequest("article");
//        indexRequest.id(article.getId().toString());
//        ObjectMapper objectMapper = new ObjectMapper();
//        String s = objectMapper.writeValueAsString(article);
//        indexRequest.source(s, XContentType.JSON);
//        IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT.toBuilder().build());

    }

    @Override
    @Transactional(rollbackFor = ParamsException.class)
    public void insertListWithEs(List<Article> articleList) throws IOException
    {
        AssertUtil.isTrue(!this.saveBatch(articleList), "添加失败");
//        BulkRequest bulkRequest = new BulkRequest();
//        for (Article article : articleList)
//        {
//            IndexRequest indexRequest = new IndexRequest("article");
//            indexRequest.id(article.getId().toString());
//            ObjectMapper objectMapper = new ObjectMapper();
//            String s = objectMapper.writeValueAsString(article);
//            indexRequest.source(s, XContentType.JSON);
//            bulkRequest.add(indexRequest);
//        }
//        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT.toBuilder().build());
//        boolean failures = bulk.hasFailures();

    }
}




